var app = getApp();
var jiangpinlist = [];
var WxParse = require('../../wxParse/wxParse.js');
Page({
  data: {
    awardsList: {},
    animationData: {},
    btnDisabled: '',
    ifchou: 1 //1是可以抽奖 其他数值（2）为抽奖中就不可以点击了
  },
  gotoList: function() {
    wx.redirectTo({
      url: '../list/list'
    })
  },
  getLottery: function() {
    if (this.data.ifchou == 1) {
      var that = this
      var awardIndex = Math.random() * 6 >>> 0;
      that.setData({
        ifchou: 2
      })
      wx.request({
        url: 'https://master.shoppingwar.cn/api/Lottery/lottery',
        data: {
          session_str: wx.getStorageSync('session_str')
        },
        method: 'POST',
        dataType: 'json',
        success: function(res) {
          if(res.data.code==200){
			  console.log(res.data.data.id);
			  //奖品的id
			  var jiangpin = res.data.data.id;
			  var weizhi;
			  // for循环获取奖品的位置
			  console.log(app.awardsConfig.awards);
			  for (var i = 0; i < app.awardsConfig.awards.length; i++) {
				  if (app.awardsConfig.awards[i].index == jiangpin) {
					  weizhi = i;
				  }
			  }
			  awardIndex = weizhi;
			  // 获取奖品配置
			  var awardsConfig = app.awardsConfig,
				  runNum = 2
			  if (awardIndex < 2) awardsConfig.chance = false
			  console.log(awardIndex)

			  // 初始化 rotate
			  /*  var animationInit = wx.createAnimation({
				  duration: 10
				})
				this.animationInit = animationInit;
				animationInit.rotate(0).step()
				this.setData({
				  animationData: animationInit.export(),
				  btnDisabled: 'disabled'
				})*/

			  // 旋转抽奖
			  app.runDegs = app.runDegs || 0
			  console.log('deg', app.runDegs)
			  app.runDegs = app.runDegs + (360 - app.runDegs % 360) + (360 * runNum - awardIndex * (360 / 6))
			  console.log('deg', app.runDegs)

			  var animationRun = wx.createAnimation({
				  duration: 4000,
				  timingFunction: 'ease'
			  })
			  that.animationRun = animationRun
			  animationRun.rotate(app.runDegs).step()
			  that.setData({
				  animationData: animationRun.export(),
				  btnDisabled: 'disabled'
			  })

			  // 记录奖品
			  var winAwards = wx.getStorageSync('winAwards') || {
				  data: []
			  }
			  winAwards.data.push(awardsConfig.awards[awardIndex].name + '1个')
			  wx.setStorageSync('winAwards', winAwards)

			  // 中奖提示
			  setTimeout(function () {
				  wx.showModal({
					  title: '恭喜',
					  content: '获得' + (awardsConfig.awards[awardIndex].name),
					  showCancel: false
				  })
				  if (awardsConfig.chance) {
					  that.setData({
						  btnDisabled: ''
					  })
				  }
			  }, 4000);
			  setTimeout(function () {
				  that.setData({
					  ifchou: 1
				  })
			  }, 4000)
			  that.onLoad();
		  }else{
			  wx.showToast({
				  title: res.data.msg,
				  icon: 'none',
				  mask: true,
			  })
		  }
        },
        fail: function(res) {},
        complete: function(res) {},  
      })
    }
  },
  onLoad:function(){
	  var session_str = wx.getStorageSync('session_str');//获取密钥
	  if (!session_str){
		  wx.navigateTo({
			  url: '../author/author',
		  })
	  }
  },
	onShow:function(){

		var that = this;
		wx.showLoading({
			title: '加载中',
		})
		wx.request({
      url: 'https://master.shoppingwar.cn/api/Lottery/lotteryRule',
			data: '',
			header: {},
			method: 'POST',
			dataType: 'json',
			responseType: 'text',
			success: function (res) {
				wx.hideLoading();
				WxParse.wxParse('article', 'html', res.data.data.rule, that, 5);
			},
		})
		wx.showLoading({
			title: '加载中',
		})
		wx.request({
      url: 'https://master.shoppingwar.cn/api/Lottery/rewardList',
			data: '',
			header: {},
			method: 'POST',
			dataType: 'json',
			responseType: 'text',
			success: function (res) {
				console.log(res.data);
				wx.hideLoading();
				var choujiangshuju = res.data.data;
				jiangpinlist.length=0;
				for (var i = 0; i < choujiangshuju.length; i++) {
					var lists;
					if (choujiangshuju[i].type == 1) {
						//子弹
						lists = {
							'index': choujiangshuju[i].id,
							'name': choujiangshuju[i].count + '个夺宝',
							'img': '../../img/duobao.png'
						};
					} else if (choujiangshuju[i].type == 3) {
						// 护盾
						lists = {
							'index': choujiangshuju[i].id,
							'name': choujiangshuju[i].count + '个防空',
							'img': '../../img/fangkong.png'
						};
					} else if (choujiangshuju[i].type == 2) {
						// 炸弹
						lists = {
							'index': choujiangshuju[i].id,
							'name': choujiangshuju[i].count + '个空袭',
							'img': '../../img/kongxi.png'
						};
					} else if (choujiangshuju[i].type == 4) {
						// 积分
						lists = {
							'index': choujiangshuju[i].id,
							'name': choujiangshuju[i].count + '个积分',
							'img': '../../img/index_jifen.png'
						};
					}
					jiangpinlist.push(lists);
					
				}
				
				app.awardsConfig = {
					chance: true,

					awards: jiangpinlist
				}
				console.log(app.awardsConfig.awards)
				// wx.setStorageSync('awardsConfig', JSON.stringify(awardsConfig))


				// 绘制转盘
				var awardsConfig = app.awardsConfig.awards,
					len = awardsConfig.length,
					rotateDeg = 360 / len / 2 + 90,
					html = [],
					turnNum = 1 / len // 文字旋转 turn 值
				that.setData({
					btnDisabled: app.awardsConfig.chance ? '' : 'disabled'
				})
				var ctx = wx.createContext()
				for (var i = 0; i < len; i++) {
					// 保存当前状态
					ctx.save();
					// 开始一条新路径
					ctx.beginPath();
					// 位移到圆心，下面需要围绕圆心旋转
					ctx.translate(150, 150);
					// 从(0, 0)坐标开始定义一条新的子路径
					ctx.moveTo(0, 0);
					// 旋转弧度,需将角度转换为弧度,使用 degrees * Math.PI/180 公式进行计算。
					ctx.rotate((360 / len * i - rotateDeg) * Math.PI / 180);
					// 绘制圆弧
					ctx.arc(0, 0, 150, 0, 2 * Math.PI / len, false);

					// 颜色间隔
					if (i % 2 == 0) {
						ctx.setFillStyle('rgb(255,234,176)');
					} else {
						ctx.setFillStyle('rgb(255,255,255)');
					}

					// 填充扇形
					ctx.fill();
					// 绘制边框
					ctx.setLineWidth(0.5);
					ctx.setStrokeStyle('rgba(228,55,14,.1)');
					ctx.stroke();

					// 恢复前一个状态
					ctx.restore();
					ctx.draw();

					// 奖项列表
					html.push({
						turn: i * turnNum + 'turn',
						lineTurn: i * turnNum + turnNum / 2 + 'turn',
						img: awardsConfig[i].img,
						award: awardsConfig[i].name
					});
				}
				that.setData({
					awardsList: html
				});
				wx.drawCanvas({
					canvasId: 'lotteryCanvas',
					actions: ctx.getActions()
				})
			},
		})

    // 对 canvas 支持度太差，换种方式实现

		
	},
	/**
 * 生命周期函数--监听页面隐藏
 */
	onHide: function () {
		console.log(1)
		app.awardsConfig = {
			chance: true,

			awards: []
		}

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		console.log(2)
		app.awardsConfig = {
			chance: false,
			awards: []
		}

	},
  onReady: function(e) {


  }

})